import csv
import os
from datetime import datetime
from config.config import slow_api_path  # 需确保 config.config 模块及 slow_api_path 存在


class ApiLogger(object):
    def __init__(self, filename=slow_api_path):
        self.filename = filename
        self.fieldnames = ["timestamp", "url", "method", "params", "data", "json", "response_time"]

        # 判断文件不存在或者文件里面的字符是0个的时候去写入表头
        if not os.path.exists(self.filename) or os.path.getsize(self.filename) == 0:
            with open(self.filename, 'a', newline='') as file:
                writer = csv.DictWriter(file, fieldnames=self.fieldnames)
                writer.writeheader()


    def log_request(self, url, method, params, data, json, response_time):
        # 慢接口定义，假设我这里定义慢接口是响应时间大于100ms
        if response_time >= 100:
        # if response_time >= 1:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            request_data = {
                "timestamp": timestamp,
                "url": url,
                "method": method,
                "params": params,
                "data": data,
                "json": json,
                "response_time": response_time
            }

            with open(self.filename, 'a', newline='') as file:
                writer = csv.DictWriter(file, fieldnames=self.fieldnames)
                writer.writerow(request_data)